import nacos
from django.conf import settings
import os
import redis
import yaml

redis_config = None
redis_client = None


def load_config():
    if os.environ.get('NACOS_SERVER'):
        global redis_config
        if redis_config:
            return redis_config
        # Nacos 服务器信息
        SERVER_ADDRESSES = os.environ.get('NACOS_SERVER')
        # 创建 Nacos 客户端实例
        client = nacos.NacosClient(
            SERVER_ADDRESSES, namespace=os.environ.get('NACOS_NAMESPACE', "public"))
        return client

    # 可以添加监听器来处理配置更新


def on_config_change(config):
    # 更新 Django 配置
    print(config)
    pass


def get_mysql_config():
    client = load_config()
    if not client:
        return None
    data_id = "mysql_config"
    group = "DEFAULT_GROUP"
    client.add_config_watcher(data_id, group, on_config_change)
    yaml_config = client.get_config(data_id, group)
    if yaml_config:
        mysql_config = yaml.safe_load(yaml_config)
        mysql_config = mysql_config["MYSQL"]
        return mysql_config


mysql_config = get_mysql_config()

# 获取redis配置


def get_redis():
    global redis_client
    if redis_client:
        return redis_client
    client = load_config()
    data_id = "redis_config"
    group = "DEFAULT_GROUP"
    client.add_config_watcher(data_id, group, on_config_change)
    yaml_config = client.get_config(data_id, group)
    if yaml_config:
        redis_config = yaml.safe_load(yaml_config)
        print(redis_config)
        redis_config = redis_config["REDIS"]
        redis_client = redis.StrictRedis(
            host=redis_config['HOST'],
            port=redis_config['PORT'],
            password=redis_config['PASSWORD'],
            db=0,  # 你可以根据你的需要选择不同的数据库
        )
        return redis_client
